/*******************************************************************************
* 1. 시 스 템 : 농협보험 이미지처리 시스템
* 2. 프로그램 : COMUtil.java
* 3. 개 요 : 공통 유틸
* 4. 작 성 자 : 손 영휘
* 5. 작 성 일 : 2011. 09. 30
* 6. 소스버전 : 1.0 
********************************************************************************/

package com.nhim.utility;

import java.io.*;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.*;
import java.util.*;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

import com.nhim.common.*;
import com.nhim.utility.Base64Util;


public class COMUtil {
	
	public static String HOSTNAME = "";
	public static String LOG_DIR = "";
	public static String WORKDIR_ROOT = "";

	public static String LICLM_AGENT_SLEEP_TIME = "";
	public static String LINEB_AGENT_SLEEP_TIME = "";
	
	/* ================ 암복호화 ========================== */
	public static final int kBufferSize = 8192;
	public static Key key = null;
	public static final String defaultkeyfileurl = "defaultkey.key";
	
	/* ============= DATABASE Environment ============== */
	public static String DB_DRIVER = "";
	public static String DB_URL = "";
	public static String DB_USER = "";
	public static String DB_PASSWD = "";
	public static String DB_LOGPATH = "";
	public static int DB_MINCONNECTIONS = 5;
	public static int DB_MAXCONNECTIONS = 30;
	
	public static String LOG_DEL_TIME = "";

	public final static String FILE_SEPARATOR = System.getProperty("file.separator");
	
	/**
	 * 환경파일값을 세팅한다.
	 * @param env
	 */
	public static void SetAgentValue(CAgentEnv env) {
	    
		HOSTNAME			= env.HOSTNAME;
		LOG_DIR  			= env.LOG_DIR ;
		WORKDIR_ROOT		= env.WORKDIR_ROOT;
		
		LICLM_AGENT_SLEEP_TIME = env.liClmAgentSleepTime;
		LINEB_AGENT_SLEEP_TIME = env.liNebAgentSleepTime;
		
		DB_DRIVER			= env.dbDriver;
		DB_URL				= env.dbUrl;
		DB_USER				= env.dbUser;
		DB_PASSWD			= env.dbPasswd;
		DB_LOGPATH			= env.dbLogPath;
		DB_MINCONNECTIONS 	= env.minConnections;
		DB_MAXCONNECTIONS 	= env.maxConnections;
		
		LOG_DEL_TIME		= env.logDelTime;
		
		COMUtil.debug("========================[Program Env]==============================");
		
		COMUtil.debug("LOG_DIR      		: " + LOG_DIR);
		COMUtil.debug("WORKDIR_ROOT    		: " + WORKDIR_ROOT);
		
		COMUtil.debug("DB_DRIVER      		: " + DB_DRIVER);
		COMUtil.debug("DB_URL      			: " + DB_URL);
		COMUtil.debug("DB_USER				: " + DB_USER);
		COMUtil.debug("DB_PASSWD  			: " + DB_PASSWD);
		COMUtil.debug("DB_LOGPATH  			: " + DB_LOGPATH);
		COMUtil.debug("DB_MINCONNECTIONS  	: " + DB_MINCONNECTIONS);
		COMUtil.debug("DB_MAXCONNECTIONS	: " + DB_MAXCONNECTIONS);
				
		COMUtil.debug("===================================================================");
	}


	public static Vector vecFilePath = new Vector();
	public static Vector vecDirPath = new Vector();
	
	
	/**
	 * 디렉토리를 생성한다.
	 * @param path 경로
	 * @return boolean
	 */
	public static boolean mkDir(String path) {
		File file = new File(path);
		
		if(!file.getParentFile().isDirectory()) {
			mkDir(file.getParent());
		}		
		if(file.getName().indexOf('.') == -1) {
			file.mkdir();
		}
		return true;
	}
	
	public static void main(String args[]) throws IOException, Exception{	
		mkDir("/test/test1/test2/test3/test4/test5/test6/test7/aaaa.jsp");
	}
	
	/**
	 * 소켓버서의 로그를 파일로 저장한다.
	 * @param szMsg
	 */
	public static void debug(String szMsg) {
	
		PrintWriter pw = null;
		try {
			String szData = ""; 
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd",Locale.KOREA); 
			Date date = new Date();
			String szDbgFile = LOG_DIR + "NHImDstbtAgent_" + sdf1.format(date) + ".log";
			
			FileOutputStream dbgStream = new FileOutputStream(szDbgFile, true);
			pw = new PrintWriter(dbgStream);
			SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss:SSS", Locale.KOREA); 
			szData += "[" + sdf.format(new Date()) + "]";  
			szData += szMsg;
			pw.println(szData); 

		} catch (IOException ioe) {
		    ioe.printStackTrace();

		} finally {
			if (pw != null)
				pw.close();
		}
	}
	
    /**
     * 비밀키 생성메소드
     * @return  File
     * @exception java.io.IOException,java.security.NoSuchAlgorithmException
     */
    public static File makekey() throws IOException,NoSuchAlgorithmException {
    	return makekey(defaultkeyfileurl);
    }
    
    public static File makekey(String filename) throws IOException, NoSuchAlgorithmException {
    	
    	String keyFilePath = WORKDIR_ROOT+"/"+defaultkeyfileurl;
    	
    	File tempfile = new File(keyFilePath);
    	KeyGenerator generator = KeyGenerator.getInstance("DES");
    	generator.init(new SecureRandom());
    	Key key = generator.generateKey();
    	ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(tempfile));
    	out.writeObject(key);
    	out.close();
    	
    	return tempfile;
    }

    /**
     * 지정된 비밀키를 가지고 오는 메서드
     * @return  Key 비밀키 클래스
     * @exception Exception
     */
    private static Key getKey() throws Exception{

    	String keyFilePath = WORKDIR_ROOT+"/"+defaultkeyfileurl;
    	
    	Key key = null;
    	
    	File file = new File(keyFilePath);
		if(file.exists()){
			ObjectInputStream in = new ObjectInputStream(new FileInputStream(keyFilePath));
			key = (Key)in.readObject();
			in.close();
		}
		else {
			COMUtil.debug(">>> [getKey] Cannot Make Key Error.");
			throw new Exception("암호키객체를 생성할 수 없습니다.");
		}
    	
    	return key;
	}

    /**
     * 문자열 대칭 암호화
     * @param   ID  비밀키 암호화를 희망하는 문자열
     * @return  String  암호화된 ID
     * @exception Exception
     */
	 public static String encrypt(String str) {
		 if ( str == null || str.length() == 0 ) 
			 return "";
		 
		 String encryptStr = "";
		 
		 try {
			 Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
			 cipher.init(Cipher.ENCRYPT_MODE,getKey());
			  
			 byte[] inputBytes1 = str.getBytes("UTF8");
			 byte[] outputBytes1 = cipher.doFinal(inputBytes1);
			 encryptStr = Base64Util.encode(outputBytes1);
		 }
		 catch(Exception e) {
			 
		 }
		 
		 return encryptStr;
	 }
 
    /**
     * 문자열 대칭 복호화
     * @param   codedID  비밀키 복호화를 희망하는 문자열
     * @return  String  복호화된 ID
     * @exception Exception
     */
	 public static String decrypt(String str) {
		 if ( str == null || str.length() == 0 ) 
			 return "";
	   
		 String strResult = "";
		 try {
			 Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
			 cipher.init(Cipher.DECRYPT_MODE, getKey());
			 
			 byte[] inputBytes1  = Base64Util.decode(str);
			 byte[] outputBytes2 = cipher.doFinal(inputBytes1);
		  
			 strResult = new String(outputBytes2,"UTF8");
		 }
		 catch(Exception e) {
			 
		 }
		 return strResult;
	 }
	 
	 
	/**
	 * 8859_1로 인코딩한다.
	 * @param str
	 * @return
	 */
    public static String encode(String str){
        String result = null;
        try{
            byte[] rawBytes = str.getBytes("KSC5601");
            result = new String(rawBytes, "8859_1");
        }catch(java.io.UnsupportedEncodingException e){
                       
        }
        return result;
     } 	

/*
	public static String getDecrypt(String decrypt){
		String encryptStr = null;
		try {
			encryptStr = RegistryPasswordUtils.decrypt(decrypt);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return encryptStr;
	}
	public static String getEncrypt(String encrypt){
		String encryptStr = null;
		try {
			encryptStr = RegistryPasswordUtils.encrypt(encrypt);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return encryptStr;
	}
*/	
	/**
	 * 현재 시간을 지정된 포맷으로 리턴한다.
	 * @param s ex)[yyyyMMddHHmmss]=>20041115130911
	 * @return String 지정되 시간
	 */
    public static String getDateFormatString(String sFormat)
    {
    	if(sFormat == null || sFormat.equals("")) return "";
    	
        SimpleDateFormat sdf1 = new SimpleDateFormat(sFormat, Locale.KOREA);
        String s1 = sdf1.format(new Date());
        
        return s1;
        /*
        int yyyy = Integer.parseInt(s1.substring(0,4));
		int mm = Integer.parseInt(s1.substring(4,6));
		int dd = Integer.parseInt(s1.substring(6,8));
		int hh = Integer.parseInt(s1.substring(8,10));
		int mi = Integer.parseInt(s1.substring(10,12));
		int ss = Integer.parseInt(s1.substring(12,14));
		
		Calendar cal = new GregorianCalendar(yyyy,mm-1,dd,hh,mi,ss);
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		cal.add(Calendar.HOUR_OF_DAY, 9);
		
		String retDateString = sdf1.format(cal.getTime());
		
        return retDateString;
        */
    }
}
